const router = require('koa-router')()
const {User} =require('../models/user')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
router.prefix('/users')

// 注册
router.post('/regUser',async (ctx)=>{
  const {userName,password} =ctx.request.body
  if(!userName || !password ){
    ctx.status = 404
    ctx.body={
      code:404,
      msg:"参数错误"
    }
    return
  }
   const res = await User.findOne({ $or: [{ userName }] })
  if(res){
   ctx.body={
    code:404,
    msg:'用户已存在'
   }
  }else{
      try {
    User.create({
      userName:userName,
      nickName:userName,
      password:md5(password)
    })
    ctx.body={
      code:200,
      msg:"创建成功"
    }
  } catch (error) {
    ctx.body={
      code:404,
      msg:"创建失败"
    }
  }
  }
})
// 登录
router.post('/login', async (ctx)=> {
  const {userName,password} =ctx.request.body
  let pws = md5(password)
  await User.findOne({"userName":userName,"password":pws},{password:0}).then(data=>{
    if([data].length>0){
      let datas =data._doc
      const token=jwt.sign({data:datas},'hyhBillData',{ expiresIn: 60 * 60 }) 
      ctx.body={
        code:200,
        msg:'ok',
        data:{...datas,token}
      }
    }else{
      ctx.body={
        code:404,
        msg:'信息错误',
      }
    }
  }).catch(err=>{
    ctx.body={
      code:500,
      msg:'错误',
      err:err
    }
  })
   

})

// 修改密码
router.post('/editPws', async (ctx)=> {
  const {userId,password} =ctx.request.body
  try {
    await User.updateOne({_id:userId},{password:md5(password)})
    ctx.body={
      code:200,
      msg:'修改成功'
    }
  } catch (error) {
    ctx.body={
      code:40001,
      msg:'修改失败',
      err:error
    }
  }
 
 
})

// 编辑用户信息
router.post('/editMsg',async (ctx)=>{
    const {userId,...parms} =ctx.request.body
    try {
      await User.updateMany({_id:userId},parms)
      ctx.body={
        code:200,
        msg:'ok'
      }
    } catch (error) {
      ctx.body={
        code:500,
        msg:'err',
        err:error
      }
    }
   
})

module.exports = router
